# -*- coding: UTF-8 -*-

from elasticsearch import Elasticsearch
from urllib3.connectionpool import xrange
from utils.log_util import LoggerUtil
import datetime
from utils.Constants import *

log = LoggerUtil.get_logger(__name__)

global_es_host = global_es_host
global_port = global_port
global_timeout = global_timeout

index_result = []

def get_total_result_by_index_prefix(prefix_index, **kwargs):
    for e in range(0, -3650, -1):
        date = (datetime.datetime.now() + datetime.timedelta(days=e)).strftime("%Y.%m.%d")
        index = prefix_index + "-" + str(date)
        try:
            get_result_by_index(index, **kwargs)
        except:
            break
    return index_result

def get_result_by_index(index, **kwargs):
    es = Elasticsearch(
        hosts = global_es_host if kwargs.get('host') is None else kwargs.get('host'),
        port = global_port if kwargs.get('port') is None else kwargs.get('port'),
        timeout = global_timeout if kwargs.get('timeout') is None else kwargs.get('timeout'))
    # gather-v10 总条数
    count = es.count(index=index)['count']
    # 每页显示条数
    page_line = 2
    # 显示多少页
    if (count % page_line == 0):
        page = (int)(count / page_line)
    else:
        page = (int)(count / page_line + 1)
    # 要生成很大的数字序列的时候，
    # 用xrange会比range性能优很多，
    # 因为不需要一上来就开辟一块很大的内存空间。
    # x = range(0,10);type(x) 是一个列表
    # x1 = xrange(0,10);type(x1) 是一个生成器 xrange(0,10)
    for x in xrange(0, page):
        rs = es.search(index=index, body={
            "query": {
                "match_all": {}
            },
            "from": x * page_line,
            "size": page_line
        })
        for hit in rs['hits']['hits']:
            log.debug(hit)
            index_result.append(hit)
    return index_result